//
//  ComposeTableViewController.swift
//  wbxm
//
//  Created by apple on 15/12/23.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD


class ComposeTableViewController: UIViewController {
    
    //自定义表情键盘视图
    private lazy var emoticonKeyboardView: EmoticonKeyboardView = EmoticonKeyboardView { [weak self](en) -> () in
        //点击的事件就可以回掉到这个地方
        
        //self?.view.backgroundColor = UIColor.redColor()
        self?.textView.insertEmoticon(en)
        
    }
    
    //响应方法放在控制器的最上面
    //选择表情键盘
    @objc private func selectEmoticonKeyboard() {
        print(__FUNCTION__)
        //想让键盘失去第一响应者
        print(textView.inputView)
        textView.resignFirstResponder()
        //使用自定义键盘 指定inpuView  系统键盘存在的时候,inputerView -- nil
        textView.inputView = textView.inputView == nil ? emoticonKeyboardView : nil
        textView.becomeFirstResponder()
        
        
    }
    //选择图片
    @objc private func selectPicture() {
        print(__FUNCTION__)
        //1隐藏键盘
        textView.resignFirstResponder()
        //2更新图片选择器的高度
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenH / 3 * 2)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
            
        }
        

    }
    
    @objc func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func send() {
        print(__FUNCTION__)
        
        var urlString = "2/statuses/update.json"

        guard let token = UserAccountMode().token else {
            SVProgressHUD.showInfoWithStatus("请重新登陆", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        let parameter = ["access_token":token,"status":textView.funllText() ?? ""]
        
        if pictureSelectorVC.imageList.count != 0 {
            //上传图片
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //调用上传图片的接口
            let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)
            NetworkTools.sharedTools.uploadImage(urlString, paramenters: parameter, imageData: imageData!, finished: { (dict, error) -> () in
                self.finishedUpdateStatus(dict, error: error)
            })
        }else {
            //发布文本微博
            NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameter) { (dict, error) -> () in
               self.finishedUpdateStatus(dict, error: error)
            }
        }
    }
    
    private func finishedUpdateStatus(dict: [String : AnyObject]? , error: NSError?) {
        if error != nil {
            SVProgressHUD.showInfoWithStatus("发布微博失败,请检查网络", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        SVProgressHUD.showInfoWithStatus("发布微博成功", maskType: SVProgressHUDMaskType.Gradient)
        self.dismissViewControllerAnimated(true, completion: nil)

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictureSelectorVC.imageList.count == 0 {
            textView.becomeFirstResponder()
        }
        
    }

    //懒加载子视图
    private lazy var textView: EmoticnTextViewsssssss = {
       
        let tv = EmoticnTextViewsssssss()
        
//        tv.text = "输入新鲜事"
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.randomeColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.delegate = self
        return tv
        
    }()
    private lazy var placeHolderLabel: UILabel = UILabel(title: "请输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var pictureSelectorVC: PictureSelectorViewController = PictureSelectorViewController()
    //析构函数
    deinit {
       NSNotificationCenter.defaultCenter().removeObserver(self)
    }
 }


extension ComposeTableViewController: UITextViewDelegate {
    
    //要实时监测文本的改变
    func textViewDidChange(textView: UITextView) {
    
        //根据textView是否有文本 隐藏占位文本 开启发送按钮的的交互
        placeHolderLabel.hidden = textView.hasText()
        
        //根据textView是否有文本 来激活发送按钮的交互
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}


extension ComposeTableViewController {
    //设置UI
    private func setupUI() {
        //设置背景色
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        setTooBar()
        
        setPictureSeletorVC()
        
        //注册通知
        registerNotification()
    }
    
    private func setPictureSeletorVC() {
        
        //首先添加视图控制器
        addChildViewController(pictureSelectorVC)
        //添加视图控制器的根视图
        view.addSubview(pictureSelectorVC.view)
        //将toolBar 移动到视图的最底层
//        view.bringSubviewToFront(toolBar)
        //设置约束和布局
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    @objc func keyboardWillChange(n:NSNotification) {
        print(n)
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //动画曲线值 为了抵消动画事件 对视图动画的影响
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        //移动toolBar位置
        let offsetY = -screenH + endRect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新的方法 必须放到动画闭包中执行
            //在动画闭包中设置动画取消值
            //需要通过原始值 来实例化枚举对象
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    //注册通知
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
  
    private func setTooBar() {
        //给toolbar 设置items 数组
        var items = [UIBarButtonItem]()
        
        //向数组中添加元素
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        //遍历配置的数组
        for item in itemSettings {
            let iamgeName = item["imageName"]
            let itemBtn = UIButton(imageName: nil, backImageName: iamgeName!)
            let barBtuttonItem = UIBarButtonItem(customView: itemBtn)
            
            if let action = item["actionName"] {
                // addTarget 可以将字符串 直接转换为 Selector类型 但是 如果传递的是参数 就无法自动包装
                itemBtn.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            //添加到数组中
            items.append(barBtuttonItem)
            
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(space)
        }
        //删除最后面那个弹簧
        items.removeLast()
        
        toolBar.items = items
        
        //添加到父视图
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
        }
    }
    
    private func setTextView() {
        //添加textView
        view.addSubview(textView)
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.top.equalTo(self.view)
            make.height.equalTo(screenH / 3)
        }
        
        //给textView添加文本
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    
    //设置导航条
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        //默认发送按钮不允许交互
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        //添加titleView
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        //自定义titileView
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17)
        let nameLabel = UILabel(title: UserAccountMode().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        
        //添加label
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}

